# import urllib
from ssl import _create_unverified_context
import json
import random
import requests
from jieba import analyse
from mimesis import Food
from faker import Faker
import urllib.request
import urllib.parse

context = _create_unverified_context()  # 屏蔽ssl证书
fake = Faker('zh_CN')
PEXELS_API_KEY = 'M4Q8vrdivlzWcDJDVuoJdbhnCrgii6ShoMSZndAY9HX4et3W6QYrRwuB'
foodm = Food('zh')
storeContent = '<div data-v-8c7b5918="" class="text-content"><i class="img-wrapper" style="padding-bottom:166%"><img src="https://t11.baidu.com/it/u=2446673225,698559744&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=1245&amp;s=0F547A861E5717E740BC05330300C042" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:100%"><img src="https://t10.baidu.com/it/u=3373800018,3037034019&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=750&amp;s=1D966C9652C273E75702D1240300E06A" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:100%"><img src="https://t10.baidu.com/it/u=3088398516,3269224923&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=750&amp;s=15826EB3528E1FE71F1428EC0300E072" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:100%"><img src="https://t12.baidu.com/it/u=30265435,2181381253&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=750&amp;s=030268A37A5A3FE74434442D03003042" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:100%"><img src="https://t10.baidu.com/it/u=1230766845,65539484&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=750&amp;s=9194789350C176F441B2403403001062" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:100%"><img src="https://t11.baidu.com/it/u=2880205970,733118762&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=750&amp;s=4B926887560307E71818647C0300A052" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:133.33333333333334%"><img src="https://t12.baidu.com/it/u=1215037053,534467661&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=1000&amp;s=2B147B870DDEBBED314DF00E03003051" loading="lazy" class="richtext-img" style="background: none;"></i><br><i class="img-wrapper" style="padding-bottom:105.73333333333333%"><img src="https://t11.baidu.com/it/u=1291156005,2264008229&amp;fm=199&amp;app=68&amp;f=JPEG?w=750&amp;h=793&amp;s=F1EABA57508EF6ED2A71895D03008063" loading="lazy" class="richtext-img" style="background: none;"></i></div>'
DEFAULT_IMAGE='https://img1.baidu.com/it/u=1718463809,3614794693&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=526'

def generate_food_info():
    storeProduct = '{"image":"http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/b73c648fb7fd45cf8782e4ca0bc28a42s2a8dpad2x.png","sliderImages":["http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/9e97ddf78f804d50b985bdcf666478ebj76hbf3gpp.jpg","http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/b9f86161d09a44d29f7e5083d402245321764lzsus.jpg"],"videoLink":"","sliderImage":"[\\"http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/9e97ddf78f804d50b985bdcf666478ebj76hbf3gpp.jpg\\",\\"http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/b9f86161d09a44d29f7e5083d402245321764lzsus.jpg\\"]","storeName":"123","storeInfo":"123","keyword":"123 123","cateIds":[246,248,258,488],"cateId":"246,248,258,488","unitName":"123","sort":0,"giveIntegral":0,"ficti":0,"isShow":false,"isBenefit":false,"isNew":true,"isGood":false,"isHot":true,"isBest":false,"tempId":1,"attrValue":[{"image":"http://127.0.0.1:8080/crmebimage/public/maintain/2021/12/25/b73c648fb7fd45cf8782e4ca0bc28a42s2a8dpad2x.png","price":0,"cost":0,"otPrice":0,"stock":0,"barCode":"","weight":0,"volume":0,"attrValue":"{\\"规格\\":\\"默认\\"}"}],"attr":[{"attrName":"规格","attrValues":"默认","id":0}],"selectRule":"","isSub":false,"content":"<p>12356</p>","specType":false,"id":0,"couponIds":[],"coupons":[],"activity":["默认","秒杀","砍价","拼团"]}'

    storeProduct = json.loads(storeProduct)

    name = foodm.dish()  # fake.food_name()
    price = round(random.uniform(5, 50), 2)
    image_url = get_food_image_url(name)
    slide_images = [
        get_food_image_url(name),  # get_food_image_url(), #
        get_food_image_url(name)
        # get_food_image_url(name)
    ]
    details = fake.paragraph(nb_sentences=random.randint(3, 5))

    storeProduct['image'] = image_url
    storeProduct['storeName'] = name
    storeProduct['unitName'] = "随机生成食品数据"  # name
    storeProduct["attrValue"][0]["image"] = image_url
    storeProduct["attrValue"][0]["price"] = price
    storeProduct["attrValue"][0]["otPrice"] = price
    # print("y")
    # keywords = analyse.extract_tags(details, topK=3, withWeight=True, allowPOS=())
    storeProduct["sliderImages"] = slide_images
    storeProduct["sliderImage"] = "[" + slide_images[0] + "," + slide_images[1] + "]"
    storeProduct["keyword"] = name
    # for tuple in keywords:
    #     storeProduct["keyword"] = storeProduct["keyword"] + " " + tuple[0]
    storeProduct["storeInfo"] = details
    storeProduct['content'] = storeContent

    return storeProduct


def get_food_image_url(keyword):
    # url = f'https://api.pexels.com/v1/search?query={keyword}&per_page=30'
    query = 'tn=resultjson_com&logid=8891460053081208254&ipn=rj&ct=201326592&is=&fp=result&fr=&word='+keyword+'&queryWord='+keyword+'&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&expermode=&nojc=&isAsync=&pn=30&rn=30&gsm=1e&1685515555265='
    url='https://image.baidu.com/search/acjson?'+query
    # headers = {'Authorization': PEXELS_API_KEY}
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.188 Safari/537.36 CrKey/1.54.250320',
        'Referer': 'https://image.baidu.com/search/index',
        # 'Cookie:': 'BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; path=/; domain=.baidu.com'
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            data = response.json()
            # print(data)
            if len(data['data']) > 0:
                photos = data['data']
                photo = photos[random.randint(0,15)] #random.choice(photos)
                print(photo)
                if 'hoverURL' in photo:
                    return photo['hoverURL']
                elif 'middleURL' in photo:
                    return photo['middleURL']
                else:
                    return DEFAULT_IMAGE
    except Exception as e:
        print("搜索图片失败")
        print(e)
        return DEFAULT_IMAGE
        # if data['total_results'] > 0:
        #     photos = data['photos']
        #     photo = random.choice(photos)
        #     return photo['src']['medium']
    return DEFAULT_IMAGE


# 943个用户对1682.爬取了267个，还要随机生成  1682-267=1415 item
# 150*9 + 65 = 1415 item
#爬了第1轮（0，1） 第二轮x从1开始（1，9）
#全部9轮完成
for x in range(0):
    storeProductL = []
    for i in range(150):
        storeFood = generate_food_info()
        storeProductL.append(storeFood)
    # 将美食信息写入JSON文件
    with open(f'../foodJsonData/foodStoreDataVirtual{x}.json', 'w', encoding='utf-8') as f:
        json.dump(storeProductL, f, ensure_ascii=False, indent=4)
    print(f'美食信息已写入文件 foodStoreDataVirtual{x}.json。第{x}轮完成，进入{x+1}.........')

# 这个单独一轮 (9,10)已完成
# for x in range(9,10):
#     storeProductL = []
#     for i in range(65):
#         storeFood = generate_food_info()
#         storeProductL.append(storeFood)
#     # 将美食信息写入JSON文件
#     with open(f'../foodJsonData/foodStoreDataVirtual{x}.json', 'w', encoding='utf-8') as f:
#         json.dump(storeProductL, f, ensure_ascii=False, indent=4)
#     print(f'美食信息已写入文件 foodStoreDataVirtual{x}.json。第{x}轮完成')

#再加一点数据 加一轮10-11 生成100条
for x in range(10,11):
    storeProductL = []
    for i in range(100):
        storeFood = generate_food_info()
        storeProductL.append(storeFood)
    # 将美食信息写入JSON文件
    with open(f'../foodJsonData/foodStoreDataVirtual{x}.json', 'w', encoding='utf-8') as f:
        json.dump(storeProductL, f, ensure_ascii=False, indent=4)
    print(f'美食信息已写入文件 foodStoreDataVirtual{x}.json。第{x}轮完成')

# json_str = json.dumps(foods, ensure_ascii=False)
# print(json_str)
